<?php
class Enregistrement//**********************************************************
{
	var $db; 		// Ressources base de données
	var $id; 		// Identifiant
	var $table; 	// Nom de la table
	var $key; 		// Champ clé
	var $attribut; 	// Les attributs courant
	var $origine; 	// Les attributs d'origine
	var $defaut;	// Les attributs par défaut
	var $erreurs;	// Les messages d'erreurs
	var $externes;	// Les champs sur d'autres tables, gérés par les hérités
	var $dates;		// Les champs date
	var $onglet;

	// Constructeur
	function __construct($db, $table, $key)//-----------------------------------
	{
		$this->db = $db;
		$this->table = $table;
		$this->key = $key;
		$this->attribut = Array();
		$this->origine = Array();
		$this->externes = Array();
		$this->dates = Array();
		foreach ($this->defaut as $key => $value)
			$this->erreurs[$key] = '';
	}//--------------------------------------------------------------__construct

	function cle()
	{
		return $this->attribut[$this->key];
	}

	// Remplit les attributs par les valeurs par défaut    
    function Nouveau()//--------------------------------------------------------
    {
		// Attribution des valeurs
        $this->origine = $this->defaut;
		// Copie vers les valeurs de travail
		$this->Annuler();
        return TRUE;
    }//------------------------------------------------------------------Nouveau


	// Verification des attributs via la base
	function Verification()//---------------------------------------------------
	{

	}//-------------------------------------------------------------Verification

	function VerifOk()//--------------------------------------------------------
	{
		return ( implode( '', $this->erreurs ) == '' );
	}//------------------------------------------------------------------VerifOk
	
	// Réinitialise les valeurs avec celles d'origine
	function Annuler()//--------------------------------------------------------
	{
		$this->attribut = $this->origine;
    }//------------------------------------------------------------------Annuler


	// Extrait les données de la base
	// TODO select * -> select champs
    function Lire($id)//--------------------------------------------------------
    {
		$this->id = $id;
        if ($this->id == -1)
		{
            return $this->Nouveau();
		}
        else
        {
			$champs = Array();
			foreach ($this->defaut as $champ => $valeur)
			{
				if ( !in_array($champ, $this->externes) ){
					if ( array_key_exists($champ, $this->dates) ){
						$champs[] = "DATE_FORMAT($champ, '{$this->dates[$champ][0]}') as $champ";
					}
					else{
						$champs[] = $champ;
					}
				}
			}	
			$sql = 'SELECT '.implode(', ', $champs).
					" FROM {$this->table}".
					" WHERE {$this->key}='$id'";
            if ($result = $this->db->query($sql))
                if ($result->num_rows)
                {
                    $row=$result->fetch_assoc();
					foreach ($row as $champ => $valeur){
						$this->origine[$champ] = $valeur;
					}
					$this->Annuler();
                    return TRUE;
                }
        }
		return FALSE;
    }//---------------------------------------------------------------------Lire


	// Ecrit les données dans la base
    function Ecrire(){
		$sql = '';
		if ($this->id == -1 ){
			$champs = array();
			$valeurs = array();
			foreach ($this->attribut as $champ => $valeur){
				if ( $champ!=$this->key && !in_array($champ, $this->externes)){
					if (array_key_exists($champ, $this->dates)){
						$champs[] = $champ;
						$tab = explode('/',$valeur);
						$valeurs[] = "'".$tab[2].'-'.$tab[1].'-'.$tab[0].' 00:00:00'."'";
					}
					else{
						$champs[] = $champ;
						$valeurs[] = "'".$valeur."'";
					}
				}
			}	
			$sql = "INSERT INTO {$this->table} ".
					"(".implode(',',$champs).")".
					"VALUES (".implode(',',$valeurs).")";
			$retour = $this->db->query($sql);
			$this->attribut[$this->key] = $this->db->insert_id();
			return $retour;
		}
		else{
			$set = '';
			foreach ($this->attribut as $champ => $valeur){
				if ( $champ!=$this->key){
					if (!in_array($champ, $this->externes)){
						if ($this->attribut[$champ] != $this->origine[$champ]){
							if (array_key_exists($champ, $this->dates)){
								$tab = explode('/',$valeur);
								$valeur = $tab[2].'-'.$tab[1].'-'.$tab[0].' 00:00:00';
							}
							//tinymce
							$valeur = $this->db->connect_id->real_escape_string($valeur);
							$set .= "$champ = '$valeur', ";
						}
					}
				}
			}
			if ( $set != '' ){
				$sql = "UPDATE {$this->table} ".
						'SET '.substr($set,0,-2).' '.
						"WHERE {$this->key}={$this->id}";
				return $this->db->query($sql);	
			}
			else{
				return True;
			}
		}
		return False;
    }//-------------------------------------------------------------------Ecrire

	function Supprimer(){
		$sql = "DELETE FROM {$this->table} WHERE {$this->key}='{$this->id}'";
		return ( $result = $this->db->query($sql) );
	}
	
    function NomFormat($nom, $prenom=''){
		if (!empty($this->attribut[$prenom]))
			if (!empty($this->attribut[$nom]))
				return $this->attribut[$nom].', '.$this->attribut[$prenom];
			else
				return $this->attribut[$prenom];
		else
			return $this->attribut[$nom];
	}

	function LienPdf(){
	}

	function LabelChamp($champ){
		if ($champ=='rap_cli_id')
			$champ='cli_singulier';
		elseif ($champ=='rap_uti_id')
			$champ='uti_singulier';
		$label = (defined('LNG_'.strtoupper($champ)))? constant('LNG_'.strtoupper($champ)):'LNG_'.strtoupper($champ); 
		$aide = (defined('LNG_'.strtoupper($champ).'_AIDE'))? constant('LNG_'.strtoupper($champ).'_AIDE'):'LNG_'.strtoupper($champ).'_AIDE'; 
		return Array($label, $aide);
	}

	function ChoixChamp($champ){
		switch ($champ){
			case 'uti_niveau':
				return Utilisateurs::SelectDroits();
			case 'mac_cli_id':
			case 'rap_cli_id':
			case 'con_cli_id':
				return Clients::Select($this->db, -1);
			case 'mac_mod_id':
				return Modeles::Select($this->db, -1);
			case 'cli_bra_id':
				return Branches::Select($this->db, -1);
			case 'cli_uti_id':
			case 'rap_uti_id':
				return Utilisateurs::Select($this->db, -1);
			case 'cli_zon_id':
				return Zones::Select($this->db, -1);
			case 'rap_type':
				return Rapports::SelectType();
			default:
				return Array();			
		}
	}

	function ChampText($champ, $edition, $style='labelagauche'){
		list($texte, $aide) = $this->LabelChamp($champ);
        dohtml_formtext($style,
						$champ,
                        $texte,
                        $aide,
                        $edition,
                        $this->attribut[$champ],
						$this->erreurs[$champ]);
	}


	function ChampDate($champ, $edition, $style='labelagauche'){
		list($texte, $aide) = $this->LabelChamp($champ);
        dohtml_formdate($style,
						$champ,
                        $texte,
                        $aide,
                        $edition,
                        $this->attribut[$champ],
						$this->erreurs[$champ]);
	}

	function ChampSelect($champ, $edition, $style='labelagauche'){
		list($texte, $aide) = $this->LabelChamp($champ);
		$choix = $this->ChoixChamp($champ);
        dohtml_formselect($style,
						$champ,
                        $texte,
                        $aide,
                        $choix,
                        $edition,
                        $this->attribut[$champ],
						$this->erreurs[$champ]);
	}

	function ChampArea($champ, $edition, $row=4, $col=10, $style='labelagauche'){
		list($texte, $aide) = $this->LabelChamp($champ);
        dohtml_formarea($style,
						$champ,
                        $texte,
                        $aide,
                        $row,
                        $col,
                        $edition,
                        $this->attribut[$champ],
						$this->erreurs[$champ]);
	}

	function LirePost()
	{
		$keys = array_keys($_POST);
		foreach($keys as $key)
		{
			if (array_key_exists($key, $this->attribut))
			{
				$this->attribut[$key] = $_POST[$key];
			}
		}
	}

	function Contenu()
	{
		return ;
	}

	function Traitement()
	{
		if ( isset( $_POST['maj_infos'] ) )
		{
			$this->LirePost();
			$this->Verification();
			if ( $this->VerifOk() )
				if ( $this->Ecrire() )
				{
					$_SESSION[SES_STATUT] = LNG_STA_MAJ_0;
					return True;
				}
				else
					$_SESSION[SES_STATUT] = LNG_STA_ERREUR.LNG_STA_MAJ_1;
					return False;
		}
	}

	function InitErreur()
	{
	}
}//***************************************************************Enregistrement
?>
